package durst.data.json;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import net.sourceforge.stripes.util.UrlBuilder;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.mapper.helper.SimpleMapperHelper;
import com.sdicons.json.model.JSONValue;
import com.sun.xml.internal.bind.CycleRecoverable.Context;

import durst.data.CSDMessage;
import durst.data.FileAccess;
import durst.data.dao.DaoFactory;

public class FileJSONHelper implements SimpleMapperHelper {

	@Override
	public Class<FileAccess> getHelpedClass() {
		return FileAccess.class;
	}

	@Override
	public JSONValue toJSON(Object aPojo) throws MapperException {
		if (aPojo instanceof FileAccess && aPojo != null) {
			FileAccess file = (FileAccess)aPojo;
			
			if (file.getName() == null)
				try {
					DaoFactory.getInstance().createDao(FileAccess.class).refresh(file);
				}
				catch (SQLException e) {
					throw new MapperException("could not refresh FileAccess object from DB!");
				}
			
			UrlBuilder url = new UrlBuilder(Locale.ENGLISH, "action/bucket/", false);
			url.addParameter("account.id", file.getOwner().getId());
			url.addParameter("event.id", file.getEvent().getId());
			url.addParameter("filename", file.getName());
			url.setEvent("stream");
			
			Map<String, String> map = new HashMap<String, String>();
			map.put("href", url.toString());
			map.put("filename", file.getName());
			
			return JSONMapper.toJSON(map);
		}
		
		return null; 
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object toJava(JSONValue aValue, Class aRequestedClass) throws MapperException {
		return null;
	}

}
